<template>
  <div class="user-list">
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" v-model="dialogVisible" style="width:500px;padding:50px;">
      <el-form :model="newUser" ref="formRef" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userUsername">
          <el-input v-model="newUser.userUsername" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword" label-width="80px">
          <el-input type="password" v-model="newUser.userPassword" placeholder="建议初始密码为6个1"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="userNickname" label-width="80px">
          <el-input v-model="newUser.userNickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <!-- 头像上传 -->
        <el-form-item label="头像" label-width="80px">
            <el-upload
                class="avatar-uploader"
                :action="'/api/upload/avatar'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
                <div style="position: relative; width: 100%; height: 100%">
                <el-avatar
                    v-if="newUser.userAvatar"
                    :src="newUser.userAvatar"
                    size="large"
                    style="width: 100px; height: 100px;"
                />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
                </div>
            </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户列表 -->
    <el-table :data="users" style="width: 100%">
      <el-table-column prop="userId" label="用户编号" width="180"></el-table-column>
      <el-table-column prop="userUsername" label="用户名称" width="180"></el-table-column>
      <el-table-column prop="userNickname" label="昵称"></el-table-column>
      <el-table-column prop="userPassword" label="密码"></el-table-column>
      <el-table-column prop="userAvatar" label="用户头像"></el-table-column>
      <el-table-column label="是否管理员">
        <template #default="scope">
            <el-tag v-if="scope.row.admin === 1" type="success">是管理员</el-tag>
            <el-tag v-else type="info">不是管理员</el-tag>
        </template>
    </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-button link type="danger" size="small" @click="deleteUser(scope.row.userId)">删除</el-button>
          <el-button link type="primary" size="small" @click="showRoleLog(scope.row.userId)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination layout="prev, pager, next" :total="total" @current-change="handlePageChange"></el-pagination>

    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button type="primary" @click="showAddDialog">新增用户</el-button>
    </div>
  </div>

  <!--分配角色的对话框-->
  <el-dialog
    v-model="roleDialogVisible"
    title="分配角色"
    width="500"
    :before-close="handleClose">
    <!-- 角色列表-->
    <el-checkbox-group v-model="checkedRoles">
      <template v-for="role in roleList" :key="role.roleId">
          <el-checkbox :label="role.roleName" :value="role.roleId" />
      </template>
    </el-checkbox-group>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="assinRole">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, onMounted,reactive } from 'vue'
import { ElMessage } from 'element-plus' // 可选：UI提示
import axios from 'axios'
// 用户功能实现
import { getUser,insertUser,updateUser,delUser,grantRole,roleById } from '../../api/user'
// 角色功能实现
import { getRoleList } from '../../api/role'
// 用户
const users = ref([])
const total = ref(0)
const queryUser = reactive({
  userUsername:'',
  currentPage:1,
  pageSize:10
})
// 角色
const roleList = ref([])
const queryRole = reactive({
  currentPage:1,
  pageSize:10
})
// 当前用户的ID
const currentUserId = ref()
// 默认关闭对话框
const dialogVisible = ref(false)
// 分配角色的对话框
const roleDialogVisible = ref(false)
// 挂载数据
onMounted(() => {
  fetchUsers()
  fetchRoles()
})
// 获取用户列表
const fetchUsers = async () => {
 
    // 获取到数据
    let response = await getUser(queryUser)
    users.value = response.data.data
    total.value = response.data.total
}
// 获取角色列表
const fetchRoles = async () =>{
  let response = await getRoleList(queryRole)
  roleList.value = response.data.data
}
// 处理分页
const handlePageChange = (currentPageValue) => {
  queryUser.currentPage = currentPageValue
  fetchUsers()
}
// 新增用户响应数据
let newUser = reactive({
  userUsername:'',
  userPassword:'',
  userNickname:'',
  userAvatar:''
})
// 清空新增页面信息
const clear=()=>{
  // 清空数据
  newUser = reactive({
    userUsername:'',
    userPassword:'',
    userNickname:'',
    userAvatar:''    
  })
}
// 显示添加用户的对话框
const showAddDialog = () => {
  clear()
  dialogVisible.value = true
}
// 添加用户 、修改用户信息
const addUser = async () => {
  if(newUser.userId){
    try {
     let response = await updateUser(newUser)
     ElMessage.success(response.message)
     dialogVisible.value = false
    } catch (error) {
      ElMessage.error("修改失败")
    }
  }else{
    try{
     let response = await insertUser(newUser)
     ElMessage.success(response.message)
     // 关闭新增框
     dialogVisible.value = false
     // 分页
     await fetchUsers()
    }
    catch(error){
     ElMessage.error("添加失败")
    }
  }
}

// 编辑用户（这里只是一个简单的实现，实际应用中需要弹出表单）
const editUser = async (user) => {
  // 显示出对话框
  dialogVisible.value = true
  // 添加模型数据
  newUser = user
}

// 删除用户
const deleteUser = async (id) => {
  if(id){try {
    let response = await delUser(id)
      ElMessage.success(response.message)
      await fetchUsers()
  } catch (error) {
    ElMessage.error("删除失败")
  }
  }
}

// 根据ID 已经选择的打勾
const checkedRoles = ref([])
//分配角色 打开分配角色对话框
const showRoleLog = async (id)=>{
  roleDialogVisible.value = true
  // 根据当前的用户ID获取角色表
  let response = await roleById(id)
  // 把当前用户的角色信息打勾
  checkedRoles.value = response.data
  currentUserId.value = id
}

// 实现分配
const assinRole = async ()=>{
  if(currentUserId.value){
    let response = await grantRole(currentUserId.value,checkedRoles.value)
    ElMessage.success(response.message)
  }
  roleDialogVisible.value = false
}

// 上传成功回调
const handleAvatarSuccess = (response, file) => {
  // 假设后端返回的数据中包含 avatarUrl 字段
  newUser.userAvatar = response.avatarUrl || URL.createObjectURL(file.raw)
}

// 上传前校验（可选）
const beforeAvatarUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < 2 // 限制大小为2MB

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }

  if (!isValidSize) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  return true
}


// 规则
const rules = {
  userUsername: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '长度必须在5-10个字符', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度必须在6-15个字符', trigger: 'blur' }
  ],
  userNickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ]
}

</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 10px;
  background-color: #fafafa;
  cursor: pointer;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
</style>
